using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;

namespace OrbitOne.CRMLyncInfoDashboard.Lync
{
    [Export(typeof(ILyncConversationProvider))]
    public class LyncConversationProvider : ILyncConversationProvider
    {
        public Regex Regex
        {
            get { return (Regex)Application.Current.Resources["Regex"]; }
        }

        public Endpoint[] GetEndpoints()
        {
            var conversation = LyncClient.GetHostingConversation() as Conversation;
            var endpoints = new[]
                                {
                                    new Endpoint("tel:+3293301522", EndpointType.Telephone),
                                    new Endpoint("sip:wimdc@orbitone.com", EndpointType.Email), 
                                    //new Endpoint("tel:+32496521346", EndpointType.Telephone)
                                };
            endpoints =
                endpoints.Select(ce => new Endpoint(Regex.Match(ce.Uri).Groups["endpoint"].Value, ce.Type)).ToArray();

            if (conversation != null)
            {
                var participants = conversation.Participants;

                var contactEndpoints =
                    participants.Where(p => !p.IsSelf).SelectMany(
                        p =>
                        ((object[])p.Contact.GetContactInformation(ContactInformationType.ContactEndpoints))
                            .Cast<ContactEndpoint>()).ToList();

                var conversationEndpoints =
                    contactEndpoints.Select(ce => new Endpoint(ce.Uri, Endpoint.GetType(ce.Type)))
                        .ToList();
                endpoints = conversationEndpoints.Select(ce => new Endpoint(Regex.Match(ce.Uri).Groups["endpoint"].Value, ce.Type)).ToArray();
            }
            return endpoints;
        }

        
    }

    public class Endpoint
    {
        public Endpoint(string uri, EndpointType type)
        {
            Uri = uri;
            Type = type;
        }

        public static EndpointType GetType(ContactEndpointType contactEndpointType)
        {
            switch (contactEndpointType)
            {
                case ContactEndpointType.WorkPhone:
                case ContactEndpointType.MobilePhone:
                case ContactEndpointType.HomePhone:
                case ContactEndpointType.OtherPhone:
                    return EndpointType.Telephone;
                default:
                    return EndpointType.Email;
            }
        }

        public string Uri { get; private set; }
        public EndpointType Type { get; private set; }
    }

    public enum EndpointType
    {
        Email,
        Telephone
    }
}
